package cn.zwz.nav.controller;

import cn.zwz.basics.baseVo.Result;
import cn.zwz.basics.security.SecurityUserDetails;
import cn.zwz.basics.utils.ResultUtil;
import cn.zwz.basics.utils.SecurityUtil;
import cn.zwz.data.entity.Role;
import cn.zwz.data.entity.User;
import cn.zwz.data.entity.UserDTO;
import cn.zwz.data.entity.UserRole;
import cn.zwz.data.service.IRoleService;
import cn.zwz.data.service.IUserRoleService;
import cn.zwz.data.service.IUserService;
import cn.zwz.data.utils.WechatUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "超级用户接口")
@RequestMapping("/zwz/superUser")
@Transactional
public class SuperUserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private SecurityUtil securityUtil;

    @RequestMapping(value = "/loginOnWebWechat", method = RequestMethod.GET)
    @ApiOperation(value = "网站前台登陆")
    public Result<String> loginOnWebWechat(@RequestParam String userName, @RequestParam String password, @RequestParam String code, @RequestParam String avatar
    ) {


        WechatUtil wechatUtil = new WechatUtil();
        String openId = wechatUtil.getOpenId(code);

//        查询数据库中是否有该用户openid
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("openid", openId); // 根据openid查询
        List<User> userList = iUserService.list(qw);
        System.out.println("userListsize: " + userList.size());
        if (userList.size() < 1) {
            //            如果没有该用户，则注册
            User u = new User();
            u.setUsername(UUID.randomUUID().toString().substring(0, 8) + "-" + userName); // 设置唯一的用户名
            u.setNickname(userName);
            u.setOpenid(openId);
            u.setAvatar(avatar);
            System.err.println("avatar: " + avatar);
            System.out.println("openid: " + u.getOpenid());
            String encryptPass = new BCryptPasswordEncoder().encode(password);
            u.setPassword(encryptPass).setType(0);
            iUserService.saveOrUpdate(u);
            QueryWrapper<Role> roleQw = new QueryWrapper<>();
            roleQw.eq("default_role", true);
            List<Role> roleList = iRoleService.list(roleQw);
            if (roleList.size() > 0) {
                for (Role role : roleList) {
                    iUserRoleService.saveOrUpdate(new UserRole().setUserId(u.getId()).setRoleId(role.getId()));
                }
            }
//            再次查询数据库中是否有该用户openid
            qw = new QueryWrapper<>();
            qw.eq("openid", openId); // 根据openid查询
            userList = iUserService.list(qw);
            if (!userList.isEmpty()) {
                User user = userList.get(0);
                String accessToken = securityUtil.getToken(user.getUsername(), true);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(new SecurityUserDetails(user), null, null);
                SecurityContextHolder.getContext().setAuthentication(authentication);
//                将用户名信息返回前端
                return new ResultUtil<String>().setData(accessToken);
            } else {
                // 处理用户不存在的情况，例如返回错误信息或抛出异常
                return ResultUtil.error("用户不存在");
            }
        } else {
            User user = userList.get(0);
            String accessToken = securityUtil.getToken(user.getUsername(), true);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(new SecurityUserDetails(user), null, null);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return new ResultUtil<String>().setData(accessToken);
        }
    }

    @RequestMapping(value = "/loginOnWeb", method = RequestMethod.GET)
    @ApiOperation(value = "网站前台登陆")
    public Result<String> loginOnWeb(@RequestParam String mobile, @RequestParam String password) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("mobile", mobile); // 根据姓名查询
        List<User> userList = iUserService.list(qw);
        if (userList.size() < 1) {
            return ResultUtil.error("用户不存在");
        }
        User user = userList.get(0);
        if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            return ResultUtil.error("密码不正确");
        }
        String accessToken = securityUtil.getToken(user.getUsername(), true);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(new SecurityUserDetails(user), null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new ResultUtil<String>().setData(accessToken);
    }

    @RequestMapping(value = "/reOnWeb", method = RequestMethod.GET)
    @ApiOperation(value = "网站前台注册")
    public Result<String> reOnWeb(@RequestParam String userName, @RequestParam String mobile, @RequestParam String password) {
        QueryWrapper<User> qw = new QueryWrapper<>();  //
        qw.eq("mobile", mobile); // 根据手机号查询
        User existingUser = iUserService.getOne(qw);
        if (existingUser != null) {
            return ResultUtil.error("手机号已存在");
        }
        qw.eq("nickname", userName); // 根据姓名查询
        qw.and(wrapper -> wrapper.eq("username", userName).or().eq("mobile", mobile)); // 根据姓名或手机号查询
        Long userCount = iUserService.count(qw); // 查询用户数量
        if (userCount > 0) {
            return ResultUtil.error("用户已存在");
        }
        User u = new User();
        u.setUsername(UUID.randomUUID().toString().substring(0, 8) + "-" + userName); // 设置唯一的用户名
        u.setNickname(userName);
        u.setMobile(mobile);
        u.setEmail(u.getMobile() + "@qq.com");
        String encryptPass = new BCryptPasswordEncoder().encode(password);
        u.setPassword(encryptPass).setType(0);
        iUserService.saveOrUpdate(u);
        QueryWrapper<Role> roleQw = new QueryWrapper<>();
        roleQw.eq("default_role", true);
        List<Role> roleList = iRoleService.list(roleQw);
        if (roleList.size() > 0) {
            for (Role role : roleList) {
                iUserRoleService.saveOrUpdate(new UserRole().setUserId(u.getId()).setRoleId(role.getId()));
            }
        }
        System.err.println("u.getUsername():" + u.getUsername());
        String accessToken = securityUtil.getToken(u.getUsername(), true);


        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(new SecurityUserDetails(u), null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new ResultUtil<String>().setData(accessToken);
    }

    @RequestMapping(value = "/getMyInfo", method = RequestMethod.GET)
    @ApiOperation(value = "查询我的信息")
    public Result<UserDTO> getMyInfo() {
        String id = securityUtil.getCurrUser().getId();
        User byId = iUserService.getById(id);
        UserDTO userDTO = new UserDTO();
        userDTO.setId(byId.getId());
        userDTO.setUsername(byId.getUsername());
        userDTO.setNickname(byId.getNickname());
        userDTO.setMobile(byId.getMobile());
        userDTO.setSex(byId.getSex());
        userDTO.setAddress(byId.getAddress());
        userDTO.setEmail(byId.getEmail());
        userDTO.setAvatar(byId.getAvatar());
        userDTO.setCreateTime(byId.getCreateTime());
        userDTO.setUpdateTime(byId.getUpdateTime());
        return new ResultUtil<UserDTO>().setData(userDTO);
    }

    @RequestMapping(value = "/setMyInfo", method = RequestMethod.GET)
    @ApiOperation(value = "修改我的信息")
    public Result<User> setMyInfo(@RequestParam String id, @RequestParam String nickname, @RequestParam String mobile, @RequestParam String sex, @RequestParam String address, @RequestParam String email) {
        User user = iUserService.getById(id);
        if (user == null) {
            return ResultUtil.error("用户不存在");
        }
        user.setNickname(nickname);
        user.setMobile(mobile);
        user.setSex(sex);
        user.setAddress(address);
        user.setEmail(email);
        iUserService.saveOrUpdate(user);
        return new ResultUtil<User>().setData(user);
    }

    //员工登录
    @RequestMapping(value = "/ygOnWeb", method = RequestMethod.GET)
    public Result<String> ygOnWeb(@RequestParam String username, @RequestParam String password) {
        System.err.println(username);
        System.err.println(password);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", username);
        List<User> userList = iUserService.list(qw);
        if (userList.size() < 1) {
            return ResultUtil.error("用户不存在");
        }
        User user = userList.get(0);
        if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            return ResultUtil.error("密码不正确");
        }
        String accessToken = securityUtil.getToken(user.getUsername(), true);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(new SecurityUserDetails(user), null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new ResultUtil<String>().setData(accessToken);
    }
}
